import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:razer_one/app/main/utils/alert_utils.dart';

class PermissionUtil {
  static showImagePicker(
    BuildContext context, {
    ImageSource source = ImageSource.camera,
    double? maxWidth = 1000,
    double? maxHeight = 1000,
  }) async {
    {
      if (source == ImageSource.camera) {
        if (await checkPermissionCamera(context) == false) return null;
      } else {
        if (await checkPermissionPhotos(context) == false) return null;
      }
      XFile? pickedFile = await ImagePicker().pickImage(
        source: source,
        // imageQuality: 90,
        // maxHeight: 1000,
        // maxWidth: 1000,
      );

      return pickedFile;
    }
  }

  // 检查照相机权限
  static Future<bool> checkPermissionCamera(
    BuildContext context, {
    bool isShowAlert = true,
  }) async {
    PermissionStatus status = await Permission.camera.status;
    if (status.isDenied) {
      status = await Permission.camera.request();
    }
    if (!status.isGranted) {
      if (isShowAlert) {
        AlertUtils.atcionsShow(context, "没有开启相机权限", content: "前往开启",
            confirmHandle: () {
          openAppSettings();
        });
      }
      return false;
    }
    return true;
  }

  // 检查相册权限
  static Future<bool> checkPermissionPhotos(
    BuildContext context, {
    bool isShowAlert = true,
  }) async {
    PermissionStatus status = Platform.isIOS
        ? (await Permission.photos.status)
        : (await Permission.storage.status);

    if (status.isDenied) {
      status = Platform.isIOS
          ? (await Permission.photos.request())
          : (await Permission.storage.request());
    }
    if (!status.isGranted && !status.isLimited) {
      if (isShowAlert) {
        AlertUtils.atcionsShow(context, "没有相册权限", content: "前往开启",
            confirmHandle: () {
          openAppSettings();
        });
      }
      return false;
    }
    return true;
  }

  /// 检查保存图片权限
  static Future<bool> checkPermissionSavePhoto(
    BuildContext context, {
    bool isShowAlert = true,
  }) async {
    PermissionStatus status = Platform.isIOS
        ? (await Permission.photosAddOnly.status)
        : (await Permission.storage.status);
    if (status.isDenied) {
      status = Platform.isIOS
          ? (await Permission.photosAddOnly.request())
          : (await Permission.storage.request());
    }
    if (!status.isGranted) {
      if (isShowAlert) {
        AlertUtils.atcionsShow(context, "没有相册权限", content: "前往开启",
            confirmHandle: () {
          openAppSettings();
        });
      }
      return false;
    }
    return true;
  }
}
